package models

import (
	"time"

	"gorm.io/gorm"
)

type Tag struct {
	Model

	Name       string `json:"name"`
	CreatedBy  string `json:"created_by"`
	ModifiedBy string `json:"modified_by"`
	State      int    `json:"state"`
}

func GetTags(pageNum int, pageSize int, maps interface{}) (tags []Tag) {
	db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&tags)
	return
}

func GetTagTotal(maps interface{}) (count int64) {
	db.Model(&Tag{}).Where(maps).Count(&count)
	return
}

// tag是否存在
func ExistTagByName(name string) bool {
	var tag Tag
	db.Select("id").Where("name = ?", name).First(&tag)
	return tag.ID > 0
}

// 根据id查询tag是否存在
func ExistTagByID(id int) bool {
	var tag Tag
	db.Select("id").Where("id = ?", id).First(&tag)
	return tag.ID > 0
}

// 添加tag
func AddTag(name string, state int, createdBy string) bool {
	db.Create(&Tag{Name: name, State: state, CreatedBy: createdBy})

	return true
}

//修改标签
func EditTag(id int, data interface{}) bool {
	db.Model(&Tag{}).Where("id = ?", id).Updates(data)
	return true
}

// 删除标签
func DeleteTag(id int) bool {
	db.Where("id = ?", id).Delete(&Tag{})
	return true
}

// 添加标签前添加时间
func (tag *Tag) BeforeCreate(tx *gorm.DB) error {
	tx.Model(tag).Update("CreatedOn", time.Now().Unix())

	return nil
}

// 使用Unscoped()物理删除数据
func CleanAllTag() bool {
	db.Unscoped().Where("deleted_on != ?", nil).Delete(&Tag{})
	return true
}

// func (tag *Tag) BeforeUpdate(tx *gorm.DB) error {

// 	tx.Model(tag).Where("id = ?", tag.ID).Update("ModifiedOn", time.Now().Unix())

// 	return nil
// }
